/* eslint-disable no-nested-ternary */
/* eslint-disable array-callback-return */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Col,
  Row,
  DatePicker,
  Input,
  Select,
  Table,
  message,
  Modal,
  Spin,
} from 'antd';
import router from 'umi/router';
import moment from 'moment';
import queryString from 'query-string';
import { cloneDeep } from 'lodash';
import HOCSelect from '@/components/AntDesign/Select';
import styles from '@/utils/utils.less';
import FooterToolbar from '@/components/FooterToolbar';
import DescriptionList from '@/components/DescriptionList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DictCode from '../../components/DictCode';

const { Option } = Select;
const { MonthPicker } = DatePicker;
const FormItem = Form.Item;
const { Description } = DescriptionList;

@connect(({ reducemp, loading }) => ({
  minusList: reducemp.minusList, // 回显所有数据
  deduPdInfoList: reducemp.deduPdInfoList, // 产品
  deduInsInfoList: reducemp.deduInsInfoList, // 险种
  loading:
    loading.effects['reducemp/fetchminusList'] ||
    loading.effects['reducemp/pageMinusSubmit'] ||
    loading.effects['reducemp/minusValidation'] ||
    loading.effects['reducemp/minusOver'] ||
    false,
  RemoveRsnList: reducemp.RemoveRsnList, // 离职原因
  overdueDateLoading: loading.effects['reducemp/minusOver'], // 超截止日信息loading
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isTelRequired: false,
      subite: true, // 分项设置
      dateflg: false,
      currentDate: null, // 当前日期
      isChange: true,
      isSubset: true,
      modalVisible: false, // 超截止日信息弹框
      assCloseDateDtoList: null, // 截止日险种信息集合
      newDeduPdInfoList: null,
    };
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    const query = queryString.parse(location.search);
    dispatch({
      type: 'reducemp/reasonsLeaving', // 离职原因
      payload: {},
    });

    dispatch({
      type: 'reducemp/fetchminusList', // 回显
      payload: { sendId: query.sendId },
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'reducemp/updateModelData',
      payload: { deduPdInfoList: [] },
    });
  }

  // 设置电话是否是选中状态
  isContact = value => {
    this.setState({ isTelRequired: value.key === '1' });
  };

  // 选择业务结束日期
  selectEndDate = date => {
    const { form } = this.props;
    this.setState({ isSubset: true, isChange: false });
    // 解析当前日期格式（每月的最后一天）
    const str = moment(date).format('YYYY-MM');
    const arr = str.split('-');
    const seperator = '-';
    // eslint-disable-next-line camelcase
    const new_date = new Date(arr[0], arr[1], 1);
    const currentDate =
      arr[0] +
      seperator +
      arr[1] +
      seperator +
      new Date(new_date.getTime() - 1000 * 60 * 60 * 24).getDate();
    this.setState({ currentDate });
    const { deduPdInfoList } = this.props;
    deduPdInfoList.forEach(item => {
      form.setFieldsValue({ [`endDate_${item.id}`]: date });
    });
  };

  // 分项设置
  subsett = record => {
    const { deduPdInfoList, deduInsInfoList, form, dispatch } = this.props;
    this.setState({ subite: false });
    const dataList = JSON.parse(JSON.stringify(deduPdInfoList));
    // eslint-disable-next-line array-callback-return
    let i = 0;
    dataList.forEach((item, index) => {
      if (item.id === 'PDINF_0000000001') {
        i = index;
        // eslint-disable-next-line no-shadow
        deduInsInfoList.map(item => {
          const temp = item;
          temp.id = item.ass;
          temp.name = item.assName;
          temp.endDate = record.endDate;
          temp.cityId = item.cityId;
          temp.cityName = item.cityName;
        });
        dataList.splice(i + 1, 0, ...deduInsInfoList);
        this.setState({ dateflg: true }, () => {
          const getFieldExecType = form.getFieldValue('sendEndDate');
          // eslint-disable-next-line no-shadow
          dataList.forEach(item => {
            if (getFieldExecType) {
              form.setFieldsValue({ [`endDate_${item.id}`]: getFieldExecType });
            }
            if (item.id === 'PDINF_0000000001' && item.endDate) {
              deduInsInfoList.forEach(value => {
                form.setFieldsValue({ [`endDate_${value.id}`]: moment(item.endDate) });
              });
            }
          });
        });
      }
    });
    dispatch({
      type: 'reducemp/updateModelData', // 离职原因
      payload: { deduPdInfoList: dataList },
    });
  };

  // 取消分项设置
  subsettcancel = () => {
    const { deduPdInfoList, deduInsInfoList, dispatch } = this.props;
    this.setState({ subite: true, dateflg: false });
    const arr = JSON.parse(JSON.stringify(deduPdInfoList));
    let i = 0;
    arr.forEach((item, index) => {
      if (item.id === 'PDINF_0000000001') {
        i = index;
        arr.splice(i + 1, deduInsInfoList.length); // 将五险的数据截取掉
      }
    });
    dispatch({
      type: 'reducemp/updateModelData', // 离职原因
      payload: { deduPdInfoList: arr },
    });
  };

  // 产品属性选择时间时，更新时间
  dateChange = (date, datestring, record) => {
    const temp = record;
    this.setState({ isChange: false, isSubset: false });
    // 解析当前日期格式（每月的最后一天）
    const str = moment(date).format('YYYY-MM');
    const arr = str.split('-');
    const seperator = '-';
    // eslint-disable-next-line camelcase
    const new_date = new Date(arr[0], arr[1], 1);
    const currentDate =
      arr[0] +
      seperator +
      arr[1] +
      seperator +
      new Date(new_date.getTime() - 1000 * 60 * 60 * 24).getDate();
    temp.endDate = currentDate;
  };

  // 处理产品分项设置数据
  processData = data => {
    const { deduPdInfoList } = this.props;
    const deduInsInfoLists = [];
    const deduPdInfoLists = [];
    deduPdInfoList.forEach(item => {
      const id = `${item.id}`;
      // PDINF_  PDEFINED_为产品前缀
      if (
        id?.toUpperCase()?.indexOf('PDINF_') > -1 ||
        id?.toUpperCase()?.indexOf('PDEFINED_') > -1
      ) {
        deduPdInfoLists.push({
          pdId: id,
          endDate: data[`endDate_${id}`] ? data[`endDate_${id}`].format('YYYY-MM-DD') : '',
          pdCate: item.pdCate,
        });
      }
      // 只有选择分项处理时会有
      else {
        deduInsInfoLists.push({
          ass: id,
          endDate: data[`endDate_${id}`] ? data[`endDate_${id}`].format('YYYY-MM-DD') : '',
        });
      }
    });
    return { deduInsInfoLists, deduPdInfoLists };
  };

  // 提交数据
  sumSubmit = () => {
    const { deduPdInfoList, minusList, dispatch, form, deduInsInfoList } = this.props;
    const { isChange, currentDate } = this.state;
    let submitData = {};
    form.validateFieldsAndScroll(async (err, values) => {
      if (!err) {
        const temp = cloneDeep(values);
        const deduInfoList = this.processData(values);
        deduPdInfoList.forEach(item => {
          delete temp[`endDate_${item.id}`];
        });
        Object.keys(values).forEach(key => {
          if (!values[key]) {
            // 不存在
            temp[key] = '';
          } else if (values[key].key) {
            // 下拉
            temp[key] = values[key].key;
          } else if (key === 'evaDate') {
            // 日期
            temp[key] = values[key].format('YYYY-MM-DD');
          } else if (key === 'sendEndDate') {
            // 年月
            temp[key] = currentDate;
          }
        });

        // 提交后台的数据
        // deduInfoList.deduPdInfoLists.map(itm => {
        //   const obj = itm;
        //   if (isChange) {
        //     obj.endDate = currentDate;
        //   } else {
        //     // 单独修改分项产品业务结束日期
        //     deduPdInfoList.forEach(itps => {
        //       if (itps.id === itm.pdId) {
        //         obj.endDate = itps.endDate;
        //       }
        //     });
        //   }
        //   if (itm.pdId === 'PDINF_0000000001') {
        //     // 社保
        //     obj.deduInsInfoList = deduInfoList.deduInsInfoLists; // 五险
        //     if (isChange) {
        //       itm.deduInsInfoList.map(children => {
        //         const childrens = children;
        //         childrens.endDate = currentDate;
        //       });
        //     } else {
        //       itm.deduInsInfoList.forEach(value => {
        //         const aa = value;
        //         deduInsInfoList.forEach(childvalue => {
        //           if (Number(childvalue.ass) === Number(value.ass)) {
        //             aa.endDate = childvalue.endDate;
        //           }
        //         });
        //       });
        //     }
        //   } else {
        //     // 公积金
        //     obj.deduInsInfoList = [];
        //   }
        // });
        const list = deduInfoList.deduPdInfoLists.map(item => {
          const obj = cloneDeep(item);
          if (isChange) {
            obj.endDate = currentDate;
          } else {
            // 单独修改分项产品业务结束日期
            deduPdInfoList.forEach(itps => {
              if (itps.id === obj.pdId) {
                obj.endDate = itps.endDate;
              }
            });
          }

          if (obj.pdId === 'PDINF_0000000001') {
            // 只有分项处理时才会走到这里，不是分项deduInsInfoLists不会有值
            // 社保;
            obj.deduInsInfoList = cloneDeep(deduInfoList.deduInsInfoLists); // 五险
            if (isChange) {
              obj.deduInsInfoList.forEach(children => {
                children.endDate = currentDate;
              });
            } else {
              obj.deduInsInfoList.forEach(value => {
                deduInsInfoList.forEach(childvalue => {
                  if (Number(childvalue.ass) === Number(value.ass)) {
                    value.endDate = childvalue.endDate;
                  }
                });
              });
            }
          } else {
            // 非社保产品
            obj.deduInsInfoList = [];
          }
          return obj;
        });
        submitData = {
          ...temp,
          sendDraftId: minusList.sendDraftId,
          deduPdInfoList: list,
        };

        // 减员前校验
        // dispatch({
        //   type: 'reducemp/minusValidation',
        //   payload: submitData,
        //   callback: response => {
        //     // frameFlag为true 显示弹框
        //     if (response.success && response.data && response.data.frameFlag) {
        //       this.setState({
        //         modalVisible: true,
        //         assCloseDateDtoList: (response.data && response.data.assCloseDateDtoList) || [],
        //         newDeduPdInfoList: response.data && response.data.deduPdInfoList,
        //       });
        //     } else if (response.success && response.data && !response.data.frameFlag) {
        //       dispatch({
        //         type: 'reducemp/minusOver', // 确定减员
        //         payload: submitData,
        //         callback: res => {
        //           if (res.success) {
        //             message.success(`${res.message || '减员成功！'}`);
        //             router.push('/customservicemanage/reduceemployee/index?activeKey=1');
        //           } else {
        //             message.warning(`${res.message || '减员失败！'}`);
        //           }
        //         },
        //       });
        //     } else {
        //       message.warning(`${response.message || '减员失败！'}`);
        //     }
        //   },
        // });

        // 优化后的一个effect走完所有异步
        const res = await dispatch({
          type: 'reducemp/pageMinusSubmit',
          payload: submitData,
        });
        const { type, response } = res;
        if (type === 'minusValidation') {
          this.setState({
            modalVisible: true,
            assCloseDateDtoList: (response.data && response.data.assCloseDateDtoList) || [],
            newDeduPdInfoList: response.data && response.data.deduPdInfoList,
          });
        } else if (type === 'minusOver') {
          if (response.success) {
            message.success(`${response.message || '减员成功！'}`);
            router.push('/customservicemanage/reduceemployee/index?activeKey=1');
          } else {
            message.warning(`${response.message || '减员失败！'}`);
          }
        } else {
          message.warning(`${response.message || '减员失败！'}`);
        }
      }
    });
  };

  // 点击按截止日自定调整
  overdueDateSubmit = () => {
    const { deduPdInfoList, minusList, dispatch, form, deduInsInfoList } = this.props;
    const { isChange, currentDate, assCloseDateDtoList, newDeduPdInfoList } = this.state;
    let submitData = {};
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const temp = cloneDeep(values);
        const deduInfoList = this.processData(values);
        deduPdInfoList.forEach(item => {
          delete temp[`endDate_${item.id}`];
        });
        Object.keys(values).forEach(key => {
          if (!values[key]) {
            // 不存在
            temp[key] = '';
          } else if (values[key].key) {
            // 下拉
            temp[key] = values[key].key;
          } else if (key === 'evaDate') {
            // 日期
            temp[key] = values[key].format('YYYY-MM-DD');
          } else if (key === 'sendEndDate') {
            // 年月
            temp[key] = currentDate;
          }
        });

        // 提交后台的数据
        deduInfoList.deduPdInfoLists.map(itm => {
          const obj = itm;
          if (isChange) {
            obj.endDate = currentDate;
          } else {
            // 单独修改分项产品业务结束日期
            deduPdInfoList.forEach(itps => {
              if (itps.id === itm.pdId) {
                obj.endDate = itps.endDate;
              }
            });
          }
          if (itm.pdId === 'PDINF_0000000001') {
            // 社保
            obj.deduInsInfoList = deduInfoList.deduInsInfoLists; // 五险
            if (isChange) {
              itm.deduInsInfoList.map(children => {
                const childrens = children;
                childrens.endDate = currentDate;
              });
            } else {
              itm.deduInsInfoList.forEach(value => {
                const aa = value;
                deduInsInfoList.forEach(childvalue => {
                  if (Number(childvalue.ass) === Number(value.ass)) {
                    aa.endDate = childvalue.endDate;
                  }
                });
              });
            }
          } else {
            // 公积金
            obj.deduInsInfoList = [];
          }
        });
        submitData = {
          ...temp,
          sendDraftId: minusList.sendDraftId,
          assCloseDateDtoList,
          deduPdInfoList: newDeduPdInfoList,
        };

        dispatch({
          type: 'reducemp/minusOver', // 确定减员
          payload: submitData,
          callback: res => {
            if (res.success) {
              message.success(`${res.message || '减员成功！'}`);
              router.push('/customservicemanage/reduceemployee/index?activeKey=1');
            } else {
              message.warning(`${res.message || '减员失败！'}`);
            }
          },
        });
      }
    });
  };

  render() {
    const {
      isTelRequired,
      currentDate,
      isSubset,
      dateflg,
      subite,
      modalVisible,
      assCloseDateDtoList,
    } = this.state;
    const {
      minusList,
      loading,
      RemoveRsnList,
      deduPdInfoList,
      deduInsInfoList,
      isChange,
      overdueDateLoading,
    } = this.props;

    const xl = { span: 8 };
    const lg = { span: 8 };
    const md = { span: 8 };
    const sm = 24;
    const colProps = { xl, lg, md, sm };
    const {
      form: { getFieldDecorator },
    } = this.props;
    // 遍历赋值（初始值）
    if (isChange) {
      this.state.currentDate = minusList.sendEndDate;
      deduPdInfoList.forEach(item => {
        const temp = item;
        temp.endDate = currentDate;
      });
    } else {
      // 如果修改了分项产品业务结束日期
      // eslint-disable-next-line no-lonely-if
      if (!isSubset) {
        deduPdInfoList.forEach(item => {
          const temp = item;
          temp.endDate = item.endDate;
        });
      } else {
        deduPdInfoList.forEach(item => {
          const temp = item;
          temp.endDate = currentDate;
        });
      }
    }

    const columns = [
      {
        title: '产品',
        dataIndex: 'name',
        width: 200,
        align: 'center',
      },
      {
        title: '执行地',
        dataIndex: 'cityName',
        width: 200,
        align: 'center',
      },
      {
        title: '执行方',
        dataIndex: 'execTypeName',
        width: 200,
        align: 'center',
      },
      {
        title: '业务结束日期',
        dataIndex: 'endDate',
        width: 400,
        align: 'center',
        render: (text, record) => (
          <div>
            <FormItem style={{ margin: 0, float: 'left', width: 120 }}>
              {getFieldDecorator(`endDate_${record.id}`, {
                rules: [{ required: true, message: '请选择' }],
                initialValue: record.endDate && moment(`${record.endDate}`, 'YYYY-MM-DD'),
              })(
                <MonthPicker
                  style={{ width: '110%' }}
                  placeholder="请选择"
                  disabled={
                    !!(
                      (record.id === 'PDINF_0000000001' && dateflg === true) ||
                      minusList.isUpdateFlag === 2
                    )
                  }
                  onChange={(date, dateString) => this.dateChange(date, dateString, record)}
                  format={record.endDate}
                />
              )}
            </FormItem>
            {record.id === 'PDINF_0000000001' && deduInsInfoList.length > 0 ? (
              subite === true ? (
                <a
                  style={{ lineHeight: '33px' }}
                  onClick={() => {
                    this.subsett(record);
                  }}
                >
                  分项设置
                </a>
              ) : (
                <a
                  style={{ lineHeight: '33px' }}
                  onClick={() => {
                    this.subsettcancel(record);
                  }}
                >
                  取消分项设置
                </a>
              )
            ) : null}
          </div>
        ),
      },
    ];

    // 超截止日期表格
    const overdueDateColumns = [
      {
        title: '执行地',
        dataIndex: 'cityName',
        width: 200,
        align: 'center',
        render: text => (text && text) || '--',
      },
      {
        title: '险种',
        dataIndex: 'assName',
        width: 200,
        align: 'center',
        render: text => (text && text) || '--',
      },
      {
        title: '报减截止日',
        dataIndex: 'colseDate',
        width: 200,
        align: 'center',
        render: text => (text && text) || '--',
      },
      {
        title: '客户填写结束日期',
        dataIndex: 'oldEndDate',
        width: 400,
        align: 'center',
        render: text => (text && moment(text).format('YYYY-MM-DD')) || '--',
      },
      {
        title: '系统允许结束日期',
        dataIndex: 'newEndDate',
        width: 400,
        align: 'center',
        render: text => (text && moment(text).format('YYYY-MM-DD')) || '--',
      },
    ];
    return (
      <Form layout="vertical">
        <PageHeaderWrapper wrapperClassName={styles.advancedForm}>
          <Spin tip="Loading..." spinning={loading}>
            <Card
              title={<span style={{ fontWeight: 'bolder' }}>基本信息</span>}
              style={{ borderBottom: 'none' }}
            >
              <DescriptionList style={{ marginBottom: 24 }}>
                <Description term="客户名称">{minusList.custName}</Description>
                <Description term="商务合同">{minusList.custContName}</Description>
                <Description term="报价单">{minusList.quoName}</Description>
                <Description term="雇员姓名">{minusList.empName}</Description>
                <Description term="证件类型">{minusList.idTypeName}</Description>
                <Description term="证件号">{minusList.idCode}</Description>
                <Description term="入职日期">{minusList.entryDate}</Description>
              </DescriptionList>
            </Card>
            <Card
              title={<span style={{ fontWeight: 'bolder' }}>减员信息</span>}
              style={{ borderBottom: 'none' }}
            >
              <Row gutter={64}>
                <Col {...colProps}>
                  <FormItem label="离职日期">
                    {getFieldDecorator('evaDate', {
                      rules: [{ required: true, message: '请选择' }],
                    })(<DatePicker placeholder="请选择" style={{ width: '100%' }} />)}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="离职原因">
                    {getFieldDecorator('evaReason', {
                      rules: [{ required: true, message: '请选择' }],
                    })(
                      <HOCSelect
                        placeholder="请选择"
                        style={{ width: '100%' }}
                        showSearch
                        optionFilterProp="children"
                      >
                        {RemoveRsnList.map(item => (
                          <Option key={item.rsgnRsnId} value={item.rsgnRsnId}>
                            {item.rsgnRsnName}
                          </Option>
                        ))}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="电话">
                    {getFieldDecorator('mobile', {
                      rules: [
                        // {
                        //   required: isTelRequired,
                        //   message: '最大限制12位',
                        //   pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/,
                        // },
                        {
                          required: isTelRequired,
                          message: '请输入11位手机号码',
                          pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
                          max: 12,
                        },
                      ],
                      initialValue: minusList.mobile ? minusList.mobile : undefined,
                    })(<Input placeholder="请输入" maxLength={12} />)}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={64}>
                <Col {...colProps}>
                  <FormItem label="业务结束日期">
                    {getFieldDecorator('sendEndDate', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue:
                        minusList.sendEndDate && moment(`${minusList.sendEndDate}`, 'YYYY-MM-DD'),
                    })(
                      <MonthPicker
                        placeholder="请选择"
                        style={{ width: '100%' }}
                        onChange={(date, dateString) => this.selectEndDate(date, dateString)}
                        format={currentDate}
                        disabled={minusList.sendEndDate && minusList.isUpdateFlag === 2}
                      />
                    )}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="是否离职联系">
                    {getFieldDecorator('unempFlag', {
                      rules: [{ required: true, message: '请选择' }],
                    })(<DictCode dictType="YES_NO_FLAG" labelInValue onSelect={this.isContact} />)}
                  </FormItem>
                </Col>
                {minusList.sendType === 1 ? null : (
                  <Col {...colProps}>
                    <FormItem label="是否终止劳动合同">
                      {getFieldDecorator('stopEmpContFlag', {
                        rules: [{ required: true, message: '请选择' }],
                      })(<DictCode dictType="YES_NO_FLAG" />)}
                    </FormItem>
                  </Col>
                )}
                <Col {...colProps}>
                  <FormItem label="办理备注">
                    {getFieldDecorator('remark', {
                      rules: [{ required: false, message: '请选择' }],
                    })(<Input placeholder="请输入" maxLength={200} />)}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Card type="inner" title="分项产品结束日期设置">
                  <Table
                    rowClassName={styles.editableRowDate}
                    style={{ width: 600 }}
                    columns={columns}
                    dataSource={deduPdInfoList}
                    rowKey={(record, index) => index}
                    bordered
                    size="middle"
                    pagination={false}
                  />
                </Card>
              </Row>
            </Card>
            <Modal
              width="1000px"
              visible={modalVisible}
              title="超截止日信息确认"
              onOk={this.overdueDateSubmit}
              onCancel={() => {
                this.setState({ modalVisible: false });
              }}
              footer={[
                <Button
                  onClick={() => {
                    this.setState({ modalVisible: false });
                  }}
                >
                  取消
                </Button>,
                <Button
                  type="primary"
                  loading={overdueDateLoading}
                  onClick={this.overdueDateSubmit}
                >
                  按照截止日自动调整
                </Button>,
              ]}
            >
              <Card>
                <Table
                  dataSource={assCloseDateDtoList}
                  columns={overdueDateColumns}
                  // rowKey={key}
                  loading={loading}
                  pagination={false}
                />
              </Card>
            </Modal>
            <FooterToolbar>
              <Button
                onClick={() => router.push('/customservicemanage/reduceemployee/index')}
                style={{ marginRight: 10 }}
              >
                取消
              </Button>
              <Button type="primary" onClick={this.sumSubmit}>
                提交
              </Button>
            </FooterToolbar>
          </Spin>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

export default TableList;
